package com.anquing.ssodemo.Interceptor;

import com.anquing.ssodemo.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public class AccessInterceptor extends HandlerInterceptorAdapter {
    Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String token = request.getParameter("token");
        log.info("经过了令牌验证拦截器");
        log.info("token:" + token);

        String requestURL = request.getRequestURL().toString();

        //本地session
//        Boolean isLogin = (Boolean)request.getSession().getAttribute("isLogin");
//        if(isLogin!=null&&isLogin){
//           return true;
//        }

        //没有令牌，重定向到认证中心的登录页
        if(token==null){
            response.sendRedirect("http://www.sso.com:8080/login?returnUrl="+requestURL+"&appName=a");
            return false;
        }

        //验证令牌
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("appName", "a");
        String verifiedResult = HttpClientUtil.sendPost("http://www.sso.com:8080/verified", map);
        if(verifiedResult!=null&&"0000".equals(verifiedResult)){
            request.getSession().setAttribute("isLogin",true);
            return true;
        }else{
            //去登录
            response.sendRedirect("http://www.sso.com:8080/login?returnUrl="+requestURL+"&appName=a");
            return false;
        }
    }
}
